package com.antdesignbackend.backend.controller;

import cn.binarywang.wx.miniapp.bean.WxMaGetLiveInfo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.CalendarDate;
import com.antdesignbackend.backend.common.MD5;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.*;
import com.antdesignbackend.backend.entity.entityVo.*;
import com.antdesignbackend.backend.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 小程序商城
 */
@Controller
@RequestMapping("/AppMall")
public class AppMallController {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    ReturnVO result = new ReturnVO();
    private Integer menuId;
    private Integer userId;
    private Integer userType;
    private String roleID;

    @Autowired
    RotationService rotationService;
    @Autowired
    ClassifyService classifyService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    AddressService addressService;
    @Autowired
    ShopOrderService shopOrderService;
    @Autowired
    ShopOrderItemService shopOrderItemService;
    @Autowired
    ShopCartService shopCartService;
    @Autowired
    UserService userService;

    /**
     *分类管理
     */
    @GetMapping("/index")
    @AuthToken
    public String index() {
        return "classify/index";
    }
    /**
     *商品管理
     */
    @GetMapping("/goods")
    @AuthToken
    public String goods() {
        return "goods/index";
    }
    /**
     *订单管理
     */
    @GetMapping("/shoporder")
    @AuthToken
    public String shoporder() {
        return "shoporder/index";
    }
    /**
     * 获得商城轮播图
     * @return
     */
    @GetMapping("/getRotationShop")
    @ResponseBody
    public ReturnVO getRotationChart(){
        ReturnVO returnVO = new ReturnVO();
        QueryWrapper<Rotation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("Status",1)
                .eq("Type",2)
                .orderByDesc("Sort");
        List<Rotation> list = rotationService.list(queryWrapper);
        if (list.size() > 0){
            //拼接图片网络路径
            List<String> urls = new ArrayList<>();
            for (Rotation rotation:list){
                if (rotation.getUrl() != null && !rotation.getUrl().equals("")){
                    rotation.setUrl(WebConfig.host+"images/"+rotation.getUrl());
                }
                urls.add(rotation.getUrl());
            }
            returnVO.setData(urls);
        }
        return returnVO;
    }
    /***
     * 前端分页查询
     *
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch(@RequestBody ClassifyVo data,HttpServletRequest request) throws SecurityException, IllegalArgumentException {
        result = new ReturnVO();
        List<ClassifyVo> datalist=new ArrayList<>();
        QueryWrapper<ClassifyVo> wrapper =new QueryWrapper<ClassifyVo>();
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        //正常查询过滤条件
        if(data.getName()!=null && !data.getName().equals("")){
            wrapper.like("name",data.getName());
        }
        //先统计满足条件的数据总数，因为sql 不包括排序
        wrapper.eq("level",1);
        wrapper.eq("parentId",0);
        int total=classifyService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= classifyService.search(wrapper.orderByDesc("sort"),new Page<>(data.getPageIndex(),data.getPageSize()));
        }
        result.setData(datalist);
        return result;
    }
    /***
     * 前端分页查询
     *
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/tableSearch2")
    @ResponseBody
    @AuthToken
    public ReturnVO tableSearch2(@RequestBody ClassifyVo data,HttpServletRequest request) throws SecurityException, IllegalArgumentException {
        result = new ReturnVO();
        List<ClassifyVo> datalist=new ArrayList<>();
        QueryWrapper<ClassifyVo> wrapper =new QueryWrapper<ClassifyVo>();
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        //正常查询过滤条件
        if(data.getParentId()!=null && !data.getParentId().equals("")){
            wrapper.like("parentId",data.getParentId());
        }
        //先统计满足条件的数据总数，因为sql 不包括排序
        wrapper.eq("level",2);
        int total=classifyService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= classifyService.search(wrapper.orderByDesc("sort"),new Page<>(data.getPageIndex(),data.getPageSize()));
        }
        result.setData(datalist);
        return result;
    }
    /**
     * 修改/新增操作的保存
     */
    @PostMapping("/save")
    @ResponseBody
    @AuthToken
    public ReturnVO save(@RequestBody ClassifyVo vo) {
        result = new ReturnVO();
        boolean b = false;
        Classify entity = new Classify();
        if(vo.getId()>0) {
            //先获取旧的数据集
            entity= classifyService.getById(vo.getId());
        }
        if(vo.getAction().equals("change")) {
            entity.setState(vo.getState());
        }else {
            //新增，修改
            entity.setName(vo.getName());
            entity.setSort(vo.getSort());
        }
        if (vo.getId() == 0) {
            //新增
            entity.setCreateTime(new Date());
            entity.setState(1);
            entity.setLevel(1);
            entity.setParentId(0);
            b = classifyService.save(entity);
        } else{
            //修改
            b = classifyService.updateById(entity);
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        } else {
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    /**
     * 修改/新增操作的保存
     */
    @PostMapping("/save2")
    @ResponseBody
    @AuthToken
    public ReturnVO save2(@RequestBody ClassifyVo vo) {
        result = new ReturnVO();
        boolean b = false;
        Classify entity = new Classify();
        if(vo.getId()>0) {
            //先获取旧的数据集
            entity= classifyService.getById(vo.getId());
        }
        if(vo.getAction().equals("change")) {
            entity.setState(vo.getState());
        }else {
            //新增，修改
            entity.setName(vo.getName());
            entity.setSort(vo.getSort());
        }
        if (vo.getId() == 0) {
            //新增
            entity.setCreateTime(new Date());
            entity.setState(1);
            entity.setLevel(2);
            entity.setParentId(vo.getParentId());
            b = classifyService.save(entity);
        } else{
            //修改
            b = classifyService.updateById(entity);
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        } else {
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    /***
     * 根据id删除
     */
    @DeleteMapping("/deleteById/{id}")
    @ResponseBody
    public ReturnVO deleteImageById(@PathVariable Serializable id) {
        result = new ReturnVO();
        if (classifyService.removeById(Integer.parseInt(id.toString())) == true) {
            result.setMessage("删除成功");
            result.setCode("200");
        } else {
            result.setMessage("删除失败");
            result.setCode("500");
        }
        return result;
    }
    /***
     * 商品详情前端分页查询
     *
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/goodsTableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO goodsTableSearch(@RequestBody GoodsVo data, HttpServletRequest request) throws SecurityException, IllegalArgumentException {
        result = new ReturnVO();
        List<GoodsVo> datalist=new ArrayList<>();
        QueryWrapper<GoodsVo> wrapper =new QueryWrapper<GoodsVo>();
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        //正常查询过滤条件
        if(data.getName()!=null && !data.getName().equals("")){
            wrapper.like("g.name",data.getName());
        }
        if(data.getClassifyId()!=null && !data.getClassifyId().equals("")){
            wrapper.eq("g.classifyId",data.getClassifyId());
        }
        if(data.getClassifyId2()!=null && !data.getClassifyId2().equals("")){
            wrapper.eq("g.classifyId2",data.getClassifyId2());
        }
        if(data.getState()!=null && !data.getState().equals("")){
            wrapper.eq("g.state",data.getState());
        }
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=goodsService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= goodsService.search(wrapper.orderByDesc("createTime"),new Page<>(data.getPageIndex(),data.getPageSize()));
            for (Goods goods:datalist){
                if (goods.getImageUrl() != null && !goods.getImageUrl().equals("")){
                    goods.setImageUrl(WebConfig.host+"images/"+goods.getImageUrl());
                }
            }
        }
        result.setData(datalist);
        return result;
    }
    /**
     * 获得所属一级分类
     */
    @ResponseBody
    @GetMapping(value = "/getClassify")
    public ReturnVO getClassify(HttpServletRequest request) {
        result = new ReturnVO();
        QueryWrapper<Classify> wrapper =new QueryWrapper<Classify>();
        wrapper.eq("state",1);
        wrapper.eq("level",1);
        wrapper.eq("parentId",0);
        List<Classify> dataList = classifyService.getBaseMapper().selectList(wrapper.orderByDesc("sort"));
        result.setData(dataList);
        return result;
    }
    /**
     * 获得所属二级分类
     */
    @ResponseBody
    @GetMapping(value = "/getClassify2")
    public ReturnVO getClassify2(@RequestParam(value = "parentId",required = false) Integer parentId,HttpServletRequest request) {
        result = new ReturnVO();
        QueryWrapper<Classify> wrapper =new QueryWrapper<Classify>();
        wrapper.eq("state",1);
        wrapper.eq("level",2);
        wrapper.eq("parentId",parentId);
        List<Classify> dataList = classifyService.getBaseMapper().selectList(wrapper.orderByDesc("sort"));
        result.setData(dataList);
        return result;
    }
    /**
     * 修改/新增操作的保存
     */
    @PostMapping("/saveGoods")
    @ResponseBody
    @AuthToken
    public ReturnVO saveGoods(@RequestBody GoodsVo vo) {
        result = new ReturnVO();
        boolean b = false;
        Goods entity = new Goods();
        if(vo.getId()>0) {
            //先获取旧的数据集
            entity= goodsService.getById(vo.getId());
        }
        if(vo.getAction().equals("change")) {
            entity.setState(vo.getState());
        }else if(vo.getAction().equals("chan")){
            entity.setIsRecommend(vo.getIsRecommend());
        }else {
            //新增，修改
            entity.setName(vo.getName());
            entity.setSynopsis(vo.getSynopsis());
            entity.setClassifyId(vo.getClassifyId());
            entity.setAmount(vo.getAmount());
            entity.setNumber(vo.getNumber());
            entity.setImageUrl(vo.getImageUrl());
            entity.setClassifyId2(vo.getClassifyId2());
            entity.setDiscount(vo.getDiscount());
            entity.setFreight(vo.getFreight());
            entity.setSurcharge(vo.getSurcharge());
            entity.setOtherFees1(vo.getOtherFees1());
            entity.setOtherFees2(vo.getOtherFees2());
        }
        if (vo.getId() == 0) {
            //新增
            entity.setCreateTime(new Date());
            entity.setState(1);
            entity.setIsRecommend(0);
            b = goodsService.save(entity);
        } else{
            //修改
            b = goodsService.updateById(entity);
        }
        if(b==true){
            result.setMessage("保存成功！");
            result.setCode("200");
        } else {
            result.setMessage("保存失败！");
            result.setCode("500");
        }
        return result;
    }
    /***
     * 根据id删除
     */
    @DeleteMapping("/delgoods/{id}")
    @ResponseBody
    public ReturnVO delgoods(@PathVariable Serializable id) {
        result = new ReturnVO();
        if (goodsService.removeById(Integer.parseInt(id.toString())) == true) {
            result.setMessage("删除成功");
            result.setCode("200");
        } else {
            result.setMessage("删除失败");
            result.setCode("500");
        }
        return result;
    }
    /**
     * 获得今日推荐商品
     */
    @ResponseBody
    @GetMapping(value = "/getRecommend")
    public ReturnVO getRecommend(@RequestParam(value = "pageIndex",required = false) Integer pageIndex,
                                 @RequestParam(value = "pageSize",required = false) Integer pageSize) {
        result = new ReturnVO();
        List<GoodsVo> datalist=new ArrayList<>();
        QueryWrapper<GoodsVo> wrapper =new QueryWrapper<GoodsVo>();
        wrapper.eq("g.state",1);
        wrapper.eq("g.isRecommend",1);
        int total=goodsService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= goodsService.search(wrapper.orderByDesc("createTime"),new Page<>(pageIndex,pageSize));
            for (Goods goods:datalist){
                if (goods.getImageUrl() != null && !goods.getImageUrl().equals("")){
                    goods.setImageUrl(WebConfig.host+"images/"+goods.getImageUrl());
                }
            }
        }
        result.setData(datalist);
        return result;
    }
    /**
     * 获得新款商品
     */
    @ResponseBody
    @GetMapping(value = "/getNewpattern")
    public ReturnVO getNewpattern(@RequestParam(value = "pageIndex",required = false) Integer pageIndex,
                                 @RequestParam(value = "pageSize",required = false) Integer pageSize) {
        result = new ReturnVO();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, -7);
        List<GoodsVo> datalist=new ArrayList<>();
        QueryWrapper<GoodsVo> wrapper =new QueryWrapper<GoodsVo>();
        wrapper.eq("g.state",1);
        wrapper.ge("g.createTime",calendar.getTime());
        int total=goodsService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= goodsService.search(wrapper.orderByDesc("createTime"),new Page<>(pageIndex,pageSize));
            for (Goods goods:datalist){
                if (goods.getImageUrl() != null && !goods.getImageUrl().equals("")){
                    goods.setImageUrl(WebConfig.host+"images/"+goods.getImageUrl());
                }
            }
        }
        result.setData(datalist);
        return result;
    }
    /**
     * 获得具体分类商品
     */
    @ResponseBody
    @GetMapping(value = "/getClassifyGoods")
    public ReturnVO getClassifyGoods(@RequestParam(value = "level",required = false) Integer level,
                                     @RequestParam(value = "classifyId",required = false) Integer classifyId,
                                     @RequestParam(value = "pageIndex",required = false) Integer pageIndex,
                                  @RequestParam(value = "pageSize",required = false) Integer pageSize) {
        result = new ReturnVO();
        List<GoodsVo> datalist=new ArrayList<>();
        QueryWrapper<GoodsVo> wrapper =new QueryWrapper<GoodsVo>();
        wrapper.eq("g.state",1);
        if(level.equals(1)){
            wrapper.eq("g.classifyId",classifyId);
        }else if(level.equals(2)){
            wrapper.eq("g.classifyId2",classifyId);
        }
        int total=goodsService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= goodsService.search(wrapper.orderByDesc("createTime"),new Page<>(pageIndex,pageSize));
            for (Goods goods:datalist){
                if (goods.getImageUrl() != null && !goods.getImageUrl().equals("")){
                    goods.setImageUrl(WebConfig.host+"images/"+goods.getImageUrl());
                }
            }
        }
        result.setData(datalist);
        return result;
    }
    /**
     * 添加收货地址
     */
    @ResponseBody
    @GetMapping(value = "/addAddress")
    public String addAddress(@RequestParam(value = "userName",required = false) String userName,
                             @RequestParam(value = "phone",required = false) String phone,
                             @RequestParam(value = "address",required = false) String address,
                             @RequestParam(value = "userId",required = false) Integer userId) {
        String result = "fail";
        Address add=new Address();
        add.setUserName(userName);
        add.setPhone(phone);
        add.setAddress(address);
        add.setUserId(userId);
        add.setCreateTime(new Date());
        Boolean b=addressService.save(add);
        if(b){
            result="success";
        }
        return result;
    }
    /**
     * 查看用户收货地址
     */
    @ResponseBody
    @GetMapping(value = "/searchAddress")
    public ReturnVO searchAddress(@RequestParam(value = "userId",required = false) Integer userId) {
        result = new ReturnVO();
        List<Address> datalist=new ArrayList<>();
        QueryWrapper<Address> wrapper =new QueryWrapper<Address>();
        wrapper.eq("userId",userId);
        datalist=addressService.list(wrapper);
        result.setData(datalist);
        return result;
    }
    /**
     * 修改用户收货地址
     */
    @ResponseBody
    @GetMapping(value = "/editAddress")
    public String editAddress(@RequestParam(value = "addressId",required = false) Integer addressId,
                              @RequestParam(value = "newAddress",required = false) String newAddress,
                              @RequestParam(value = "userName",required = false) String userName,
                              @RequestParam(value = "phone",required = false) String phone) {
        String result = "fail";
        Boolean b=false;
        Address address=addressService.getById(addressId);
        if(address!=null){
            address.setAddress(newAddress);
        }
        if(userName!=null){
            address.setUserName(userName);
        }
        if(phone!=null){
            address.setPhone(phone);
        }
        b=addressService.updateById(address);
        if(b){
            result="successs";
        }
        return result;
    }
    /**
     * 删除用户收货地址
     */
    @ResponseBody
    @GetMapping(value = "/delAddress")
    public String delAddress(@RequestParam(value = "addressId",required = false) Integer addressId) {
        String result = "fail";
        Boolean b=false;
        b=addressService.removeById(addressId);
        if(b){
            result="successs";
        }
        return result;
    }
    /**
     * 获得全部分类
     */
    @ResponseBody
    @GetMapping(value = "/getAllClassify")
    public ReturnVO getAllClassify(HttpServletRequest request) {
        result = new ReturnVO();
        QueryWrapper<Classify> wrapper =new QueryWrapper<Classify>();
        wrapper.eq("state",1);
        List<Classify> dataList = classifyService.getBaseMapper().selectList(wrapper.orderByDesc("sort"));
        List<Classify> filterList = dataList.stream().filter((Classify s) ->s.getLevel()==1 && s.getParentId()==0).collect(Collectors.toList());
        JSONArray data = new JSONArray();
        for(Classify classify:filterList){
            JSONObject obj1 = new JSONObject();
            obj1.put("id", classify.getId());
            obj1.put("name", classify.getName());
            obj1.put("sort", classify.getSort());
            List<Classify> filterList2 = dataList.stream().filter((Classify s) ->s.getLevel()==2 && s.getParentId().equals(classify.getId())).collect(Collectors.toList());
            JSONArray detail = new JSONArray();
            for(Classify classify2:filterList2){
                JSONObject obj2 = new JSONObject();
                obj2.put("id", classify2.getId());
                obj2.put("name", classify2.getName());
                obj2.put("sort", classify2.getSort());
                detail.add(obj2);
            }
            obj1.put("childClassify", detail);
            data.add(obj1);
        }
        result.setData(data);
        return result;
    }
    @PostMapping("/generateOrder")
    @ResponseBody
    public ReturnVO generateOrder(@RequestBody ShopOrderVo vo){
        result = new ReturnVO();
        result.setCode("500");
        result.setMessage("订单生成失败");
        Boolean b=false;Boolean c=false;
        ShopOrder shopOrder=new ShopOrder();
        shopOrder.setOrderNo(paymentID());
        shopOrder.setUserId(vo.getUserId());
        shopOrder.setCreateTime(new Date());
        shopOrder.setPayState(0);
        shopOrder.setPayType(0);
        shopOrder.setOrderState(0);
        if(vo.getAddressId()!=null){
            Address address=addressService.getById(vo.getAddressId());
            if(address!=null){
                shopOrder.setUserName(address.getUserName());
                shopOrder.setPhone(address.getPhone());
                shopOrder.setAddress(address.getAddress());
            }else {
                result.setMessage("收货地址信息有误");
                return result;
            }
        }
        b=shopOrderService.save(shopOrder);
        if(b){
            if(vo.getItemList().size()>0){
                Double allAmount=0.0;
                for(OrderShopVo shopVo:vo.getItemList()){
                    ShopOrderItem shopOrderItem=new ShopOrderItem();
                    shopOrderItem.setOrderId(shopOrder.getId());
                    shopOrderItem.setGoodId(shopVo.getGoodId());
                    shopOrderItem.setNumber(shopVo.getNumber());
                    shopOrderItem.setCreateTime(new Date());
                    Goods goods=goodsService.getById(shopVo.getGoodId());
                    if(goods!=null){
                        shopOrderItem.setGoodName(goods.getName());
                        shopOrderItem.setAmount(goods.getAmount());
                        Double totalAmount=(goods.getAmount()*goods.getDiscount()+goods.getFreight()+goods.getSurcharge()
                                +goods.getOtherFees1()+goods.getOtherFees2())*shopVo.getNumber();
                        allAmount=allAmount+totalAmount;
                        shopOrderItem.setTotalAmount(totalAmount);
                        shopOrderItem.setImageUrl(goods.getImageUrl());
                        shopOrderItemService.save(shopOrderItem);
                    }else {
                        result.setMessage("商品信息有误");
                        return result;
                    }
                }
                shopOrder.setTotalAmount(allAmount);
                c=shopOrderService.updateById(shopOrder);
                if(c){
                    result.setMessage("订单生成成功");
                    result.setData(shopOrder.getOrderNo());
                }
            }
        }
        return result;
    }
    //产生订单号
    public String paymentID(){
        int r1=(int)(Math.random()*(10));//产生2个0-9的随机数
        int r2=(int)(Math.random()*(10));
        long now = System.currentTimeMillis();//一个13位的时间戳
        String paymentID0 =String.valueOf(r1)+String.valueOf(r2)+String.valueOf(now);
        int r3=(int)(Math.random()*(10));//产生2个0-9的随机数
        int r4=(int)(Math.random()*(10));
        String paymentID = paymentID0 +String.valueOf(r3)+String.valueOf(r4);// 订单ID
        return paymentID;
    }
    /***
     * 订单前端分页查询
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/orderTableSearch")
    @ResponseBody
    @AuthToken
    public ReturnVO orderTableSearch(@RequestBody ShopOrderVo data,HttpServletRequest request) throws SecurityException, IllegalArgumentException {
        result = new ReturnVO();
        List<ShopOrderVo> datalist=new ArrayList<>();
        QueryWrapper<ShopOrderVo> wrapper =new QueryWrapper<ShopOrderVo>();
        userId=(Integer) request.getSession().getAttribute("UserID");
        roleID=(String) request.getSession().getAttribute("RoleID");
        //正常查询过滤条件
        if(data.getOrderNo()!=null && !data.getOrderNo().equals("")){
            wrapper.eq("orderNo",data.getOrderNo());
        }
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=shopOrderService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= shopOrderService.search(wrapper.orderByDesc("createTime"),new Page<>(data.getPageIndex(),data.getPageSize()));
        }
        result.setData(datalist);
        return result;
    }
    /***
     * 订单详情前端分页查询
     * @return
     * @throws SecurityException
     * @throws IllegalArgumentException
     */
    @PostMapping("/orderTableSearch2")
    @ResponseBody
    @AuthToken
    public ReturnVO orderTableSearch2(@RequestBody ShopOrderItem data) throws SecurityException, IllegalArgumentException {
        result = new ReturnVO();
        List<ShopOrderItem> datalist=new ArrayList<>();
        QueryWrapper<ShopOrderItem> wrapper =new QueryWrapper<ShopOrderItem>();
        //正常查询过滤条件
        if(data.getOrderId()!=null && !data.getOrderId().equals("")){
            wrapper.eq("orderId",data.getOrderId());
        }
        datalist=shopOrderItemService.list(wrapper);
        for (ShopOrderItem shopOrderItem:datalist){
            if (shopOrderItem.getImageUrl() != null && !shopOrderItem.getImageUrl().equals("")){
                shopOrderItem.setImageUrl(WebConfig.host+"/images/"+shopOrderItem.getImageUrl());
            }
        }
        result.setData(datalist);
        return result;
    }
    /**
     * 取消订单
     */
    @ResponseBody
    @GetMapping(value = "/cancelOrder")
    public String delAddress(@RequestParam(value = "orderNo",required = false) String orderNo) {
        String result = "fail";Boolean b=false;
        b=shopOrderService.update(new UpdateWrapper<ShopOrder>().set("orderState",-1).eq("orderNo", orderNo));
        if(b){
            result="success";
        }
        return result;
    }
    /**
     *  商城订单列表
     * @return
     */
    @GetMapping("/getShopOrder")
    @ResponseBody
    public Map<Object,Object> getShopOrder(@RequestParam(value = "userId",required = false) String userId) {
        Map<Object,Object> map=new HashMap<>();
        QueryWrapper<ShopOrder> wrapper =new QueryWrapper<ShopOrder>();
        wrapper.eq("userId",userId);
        List<ShopOrder> datalist=shopOrderService.list(wrapper);
        for(ShopOrder shopOrder:datalist){
            map.put("orderNo",shopOrder.getOrderNo());
            map.put("userId",shopOrder.getUserId());
            map.put("totalAmount",shopOrder.getTotalAmount());
            map.put("createTime",shopOrder.getCreateTime());
            map.put("payState",shopOrder.getPayState());
            map.put("payType",shopOrder.getPayType());
            map.put("payTime",shopOrder.getPayTime());
            map.put("orderState",shopOrder.getOrderState());
            map.put("userName",shopOrder.getUserName());
            map.put("phone",shopOrder.getPhone());
            map.put("address",shopOrder.getAddress());
            map.put("evaluate",shopOrder.getEvaluate());
            QueryWrapper<ShopOrderItem> itemWrapper =new QueryWrapper<ShopOrderItem>();
            itemWrapper.eq("orderId",shopOrder.getId());
            List<ShopOrderItem> itemdatalist=shopOrderItemService.list(itemWrapper);
            for (ShopOrderItem shopOrderItem:itemdatalist){
                if (shopOrderItem.getImageUrl() != null && !shopOrderItem.getImageUrl().equals("")){
                    shopOrderItem.setImageUrl(WebConfig.host+"/images/"+shopOrderItem.getImageUrl());
                }
            }
            map.put("itemList",itemdatalist);
        }
        return map;
    }
    /**
     * 加入购物车
     */
    @ResponseBody
    @GetMapping(value = "/addcart")
    public String addcart(@RequestParam(value = "goodId",required = false) Integer goodId,
                          @RequestParam(value = "number",required = false) Integer number,
                          @RequestParam(value = "userId",required = false) Integer userId) {
        String result = "fail";Boolean b=false;
        QueryWrapper<ShopCart> wrapper =new QueryWrapper<ShopCart>();
        wrapper.eq("userId",userId);
        wrapper.eq("goodId",goodId);
        List<ShopCart> datalist=shopCartService.list(wrapper);
        if(datalist.size()>0){
            ShopCart shopCart=datalist.get(0);
            if(number==0){
                //删除商品
                b=shopCartService.removeById(shopCart.getId());
            }else {
                //已有商品 数量增加/减少
                shopCart.setNumber(number);
                b=shopCartService.updateById(shopCart);
            }
        }else {
            //未有商品 添加商品
            ShopCart shopCart=new ShopCart();
            shopCart.setGoodId(goodId);
            shopCart.setNumber(number);
            shopCart.setUserId(userId);
            b=shopCartService.save(shopCart);
        }
        if(b){
            result="success";
        }
        return result;
    }
    /**
     * 查看购物车
     */
    @ResponseBody
    @GetMapping(value = "/viewShopCart")
    public ReturnVO viewShopCart(@RequestParam(value = "userId",required = false) Integer userId,
                                 @RequestParam(value = "pageIndex",required = false) Integer pageIndex,
                                  @RequestParam(value = "pageSize",required = false) Integer pageSize) {
        result = new ReturnVO();
        List<ShopCartVo> datalist=new ArrayList<>();
        QueryWrapper<ShopCartVo> wrapper =new QueryWrapper<ShopCartVo>();
        wrapper.eq("s.userId",userId);
        int total=shopCartService.count(wrapper);
        result.setTotal(total);
        //再查询
        if(total>0){
            datalist= shopCartService.search(wrapper,new Page<>(pageIndex,pageSize));
            for (ShopCartVo goods:datalist){
                if (goods.getImageUrl() != null && !goods.getImageUrl().equals("")){
                    goods.setImageUrl(WebConfig.host+"images/"+goods.getImageUrl());
                }
            }
        }
        result.setData(datalist);
        return result;
    }
    /**
     *  用户商城余额购买
     * @return
     */
    @PostMapping("/amountShop")
    @ResponseBody
    public WxPayMpOrderResultVO amountShop(@RequestBody ShopOrderVo orderInfoVo) {
        WxPayMpOrderResultVO payResult = new WxPayMpOrderResultVO();
        Boolean b=false;Boolean c=false;
        try{
            String key="Z11f26";
            Integer userId = orderInfoVo.getUserId();
            Integer addressId = orderInfoVo.getAddressId();
            double amount = orderInfoVo.getAmount().doubleValue();
            String sign = orderInfoVo.getSign();
            String str=String.valueOf(userId)+String.valueOf(addressId)+String.valueOf(amount)+key+"";
            String md5sign= MD5.encrypt(str);
            if(md5sign.equals(sign)){
                List<OrderShopVo> itemList=orderInfoVo.getItemList();
                //计入订单
                String orderNumner = paymentID()+"_scye";
                ShopOrder shopOrder=new ShopOrder();
                shopOrder.setOrderNo(orderNumner);
                shopOrder.setUserId(userId);
                shopOrder.setCreateTime(new Date());
                shopOrder.setPayState(1);
                shopOrder.setPayType(1);
                shopOrder.setOrderState(1);
                shopOrder.setPayTime(new Date());
                if(addressId!=null){
                    Address address=addressService.getById(addressId);
                    if(address!=null){
                        shopOrder.setUserName(address.getUserName());
                        shopOrder.setPhone(address.getPhone());
                        shopOrder.setAddress(address.getAddress());
                    }else {
                        payResult.setCode(1);
                        payResult.setMsg("收货地址信息有误");
                        return payResult;
                    }
                }
                b=shopOrderService.save(shopOrder);
                if(b){
                    if(itemList.size()>0){
                        Double allAmount=0.0;
                        for(OrderShopVo shopVo:itemList){
                            ShopOrderItem shopOrderItem=new ShopOrderItem();
                            shopOrderItem.setOrderId(shopOrder.getId());
                            shopOrderItem.setGoodId(shopVo.getGoodId());
                            shopOrderItem.setNumber(shopVo.getNumber());
                            shopOrderItem.setCreateTime(new Date());
                            Goods goods=goodsService.getById(shopVo.getGoodId());
                            if(goods!=null){
                                shopOrderItem.setGoodName(goods.getName());
                                shopOrderItem.setAmount(goods.getAmount());
                                Double totalAmount=(goods.getAmount()*goods.getDiscount()+goods.getFreight()+goods.getSurcharge()
                                        +goods.getOtherFees1()+goods.getOtherFees2())*shopVo.getNumber();
                                allAmount=allAmount+totalAmount;
                                shopOrderItem.setTotalAmount(totalAmount);
                                shopOrderItem.setImageUrl(goods.getImageUrl());
                                shopOrderItemService.save(shopOrderItem);
                            }else {
                                payResult.setCode(1);
                                payResult.setMsg("商品信息有误");
                                return payResult;
                            }
                        }
                        if(Double.doubleToLongBits(amount)!=Double.doubleToLongBits(allAmount)){
                            payResult.setCode(1);
                            payResult.setMsg("商品总价有误");
                            return payResult;
                        }
                        shopOrder.setTotalAmount(allAmount);
                        c=shopOrderService.updateById(shopOrder);
                        if(c){
                            payResult.setCode(0);
                            payResult.setMsg("商品下单成功");
                            return payResult;
                        }
                    }
                }
            }
        }catch(Exception ex) {
            log.error(ex.getMessage());
        }
        return payResult;
    }
    /**
     * 用户的商城余额
     * @param userId 用户id
     * @return
     */
    @GetMapping("/userAmount")
    @ResponseBody
    public Double userAmount(@RequestParam(value = "userId",required = false) Integer userId){
        Double userAmount=0.0;
        Users users=userService.getById(userId);
        if(users!=null){
            if(users.getShopAmount()!=null && !users.getShopAmount().equals("")){
                userAmount=userAmount+users.getShopAmount();
            }
        }
        return userAmount;
    }
}
